package com.xxx.common.web.interceptor;

import com.xxx.common.base.bo.UserTokenBO;
import com.xxx.common.base.constants.MdcKey;
import com.xxx.common.base.util.TokenUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.MDC;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

@Component
public class TokenInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        String userToken = request.getHeader(MdcKey.USER_TOKEN);

        if (StringUtils.isNotBlank(userToken)) {
            UserTokenBO userTokenBO = TokenUtil.parseToken(userToken);
            TokenUtil.setUserTokenBO(userTokenBO);
        }

        MDC.put(MdcKey.USER_TOKEN, userToken);
        return true; // 继续执行后续逻辑
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        TokenUtil.clear();
        MDC.remove(MdcKey.USER_TOKEN);
    }

}